package com.brid.KafkaProducer;


import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.serialization.Serializer;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Map;

/**
 * @Author: 司军强
 * @Date: 17:02 2019/12/19
 * @Description: 自定义kafka生产者序列化器
 */
@Slf4j
public class CompanySerializer implements Serializer<Company> {
    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {

    }

    /**
     * 将指定的数据值序列化 便于网络之间的传输
     *
     * @param topic
     * @param data
     * @return
     */
    @Override
    public byte[] serialize(String topic, Company data) {

        if (data == null) {
            return null;
        }
        //将对象转换字节
        byte[] name, address;
        try {
            if (data.getName() != null) {
                name = data.getName().getBytes("UTF-8");
            } else {
                name = new byte[0];
            }
            if (data.getAddress() != null) {
                address = data.getAddress().getBytes("UTF-8");
            } else {
                address = new byte[0];
            }
            /*ByteBuffer 字节缓冲区 缓冲io的次数
            从堆空间中分配一个容量大小为capacity的byte数组作为缓冲区的byte数据存储器
             */
            ByteBuffer buffer = ByteBuffer.allocate(4 + 4 + name.length + address.length);
            buffer.putInt(name.length);
            buffer.putInt(address.length);
            buffer.put(name);
            buffer.put(address);
            return buffer.array();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public void close() {

    }
}
